<script setup lang="ts">
import {nanoid} from 'nanoid'
import {computed, nextTick, ref} from 'vue'
import {ElMessage, type UploadRawFile} from 'element-plus'
import type {UploadProps, UploadUserFile} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import {getPart, savePart, updatePart} from '@/api/part'
import {Part} from '@/types/part.d'
const fs = require('fs')

const visible = ref(false)
const dataFormRef = ref()
const dataForm = ref<Part>(new Part())

const dataRule = ref({
    nameCn: [{
    required: true,
    message: '不能为空',
    trigger: 'blur',
  }],
})

function init(id?: number) {
    visible.value = true
    nextTick(async () => {
        if (id) {
            dataForm.value = getPart(id)
        } else {
            dataFormRef.value.resetFields()
            dataForm.value = new Part()
        }
    })
}

const emits = defineEmits(['saved'])

// 表单提交
async function dataFormSubmit() {
    console.log('save part: ', dataForm.value)

    for (let deleteImage of deleteImages.value) {
        fs.unlinkSync(`part_images/${deleteImage}`)
    }
    let images = dataForm.value.images ?? []
    images = images.filter(item => !deleteImages.value.includes(item))
    deleteImages.value.length = 0
    for (let file of uploadImages.value) {
        const arrayBuffer = await file.arrayBuffer()
        const fileBuffer = Buffer.from(arrayBuffer)
        const imageName = nanoid() + '.jpg'
        images.push(imageName)
        fs.writeFileSync(`part_images/${imageName}`, fileBuffer)
    }
    dataForm.value.images = images
    uploadImages.value.length = 0

    if (dataForm.value.id) {
        updatePart(dataForm.value)
    } else {
        savePart(dataForm.value)
    }

    visible.value = false
    emits('saved')
    ElMessage({
        type: 'success',
        message: '操作成功',
        duration: 1000,
    })
}

const fileList = computed<UploadUserFile[]>(() => {
    const images = dataForm.value.images
    if (!images) {
        return []
    }
    return images.map(value => {
        return {
            name: value,
            url: `part_images/${value}`,
        }
    })
})

const uploadImages = ref<UploadRawFile[]>([])

const handleHttpRequest: UploadProps['httpRequest'] = async (options) => {
    uploadImages.value.push(options.file)
}

const deleteImages = ref<string[]>([])

const handleRemove: UploadProps['onRemove'] = (removedImg) => {
    if (removedImg.url?.startsWith('blob')) {
        uploadImages.value = uploadImages.value.filter(value => value.uid !== removedImg.uid)
    } else {
        deleteImages.value.push(removedImg.name)
    }
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

defineExpose({
  init,
})
</script>

<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    width="500px"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="65px"
      @keyup.enter="dataFormSubmit()"
    >
      <el-form-item label="中文名" prop="nameCn">
        <el-input
          v-model="dataForm.nameCn"
          placeholder="中文名"
        />
      </el-form-item>
      <el-form-item label="英文名" prop="nameEn">
        <el-input v-model="dataForm.nameEn" placeholder="英文名"/>
      </el-form-item>
      <el-form-item label="页号" prop="pageNumber">
        <el-input
          v-model="dataForm.pageNumber"
          placeholder="页号"
        />
      </el-form-item>
      <el-form-item label="序号" prop="serialNumber">
        <el-input v-model="dataForm.serialNumber" placeholder="序号"/>
      </el-form-item>
      <el-form-item label="型号" prop="modelNumber">
        <el-input v-model="dataForm.modelNumber" placeholder="型号"/>
      </el-form-item>
      <el-form-item label="重量" prop="weight">
        <el-input v-model="dataForm.weight" placeholder="重量"/>
      </el-form-item>
      <el-form-item label="件号1" prop="partNumber1">
        <el-input v-model="dataForm.partNumber1" placeholder="件号1"/>
      </el-form-item>
      <el-form-item label="件号2" prop="partNumber2">
        <el-input v-model="dataForm.partNumber2" placeholder="件号2"/>
      </el-form-item>
    </el-form>
    <el-upload
        :file-list="fileList"
        :http-request="handleHttpRequest"
        :on-remove="handleRemove"
        :on-preview="handlePictureCardPreview"
        list-type="picture-card"
        :auto-upload="true"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
    <template v-slot:footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
